<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <title>inote 云记事</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css"/>
    <link rel="stylesheet" type="text/css" href="../css/layout.css" />
    <link rel="stylesheet" type="text/css" href="../css/component/bar.css" />
    <link rel="stylesheet" type="text/css" href="../css/component/forms.css"/>
    <link rel="stylesheet" type="text/css" href="../css/component/button.css"/>
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.css" />
    <!-- 要在头部载入 -->
    <script type="text/javascript" src="../script/jquery.min.js"></script>
    <script type="text/javascript" src="../script/mobiscroll.custom-2.16.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="../css/mobiscroll.custom-2.16.1.min.css" />
    <style>
        html,body{
            width: 100%;
            height: 100%;
        }
        #wrap{
            width: 100%;
            height: 100%;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-flex-flow: column;
        }
        #header{
            position: fixed;
            top: 0px;
            z-index: 100;
        }
        #main{
            -webkit-box-flex: 1;
            -webkit-flex: 1;
            z-index: 0;
        }
        #main{
            background-color: rgba(0,0,0,0);
            padding: 15px;
        }
        legend{
            font-size: 20px;
        }
        table{
            font-size: medium;
        }
        span{
            height: 25px;
            line-height: 25px;
        }
        .mui-btn{
            width: 100%;
            height: 48px;
            font-size: 16px;
        }
        #submit,#submit1,#submit1-1,#submit2,#submit2-1{
            margin-left: 0px;
        }
        .mui-textfield > textarea {
            min-height: 84px;
        }
        .btn:hover{
            background-color: rgba(0,0,0,0.12);
        }
        .bar-tab{
            width: 54px;
            height: 48px;
        }
        .btnActive{
            background-color: #42A5F5;
        }
        .greenBtnActive{
            background-color: #66BB6A;
        }
        .hide{
            display: none;
        }
        
    </style>
</head>
<body>
    <div id="wrap">
        <div id="header" class="ino-bar home-bar">
            <div class="title">inote</div>
            <table class="ino-bar-content">
                <tr>
                    <td>
                        <div class="bar-tab bar-tab-back" tapmode="tabActive" onclick="api.closeWin();">
                            <img class="listTab" src="../image/png/webpage/arrow_back.png">
                        </div>                        
                    </td>
                    <td class="bar-right" align="right">
                        <div class="bar-tab bar-tab-menu" tapmode="tabActive" onclick="deleteTask()">
                            <img class="listTab" src="../image/png/webpage/delete.png">
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div id="main">
            <form>
                <legend>标题</legend>
                <div class="mui-textfield">
                    <input id="title" type="text" maxlength="10">
                    <label>最多可输入10个字符</label>
                </div>
                <div class="mui-textfield">
                    <textarea id="detail"></textarea>
                    <label>详细描述</label>
                </div>
                <div id="range"></div>
                <div class="mui-textfield" id="date-start-area">
                    <input id="date-start" type="text">
                    <label>开始时间</label>
                </div>
                <div class="mui-textfield" id="date-end-area">
                    <input type="text" id="date-end">
                    <label>结束时间</label>
                </div>
            </form>
            <button id="submit" tapmode="btnActive" type="submit" class="mui-btn mui-btn--raised mui-btn--primary" onclick="submitInsert()">保存</button>
            <button id="submit2" tapmode="btnActive" type="submit" class="mui-btn mui-btn--raised mui-btn--primary hide" onclick="submitUpdate()">确认修改</button>
            <button id="submit2-1" tapmode="btnActive" type="submit" class="mui-btn mui-btn--raised mui-btn--primary hide" onclick="openToast('忘记设置结束时间啦')">确认修改</button>
        </div>
    </div>
    
</body>

<script type="text/javascript">
    // textarea获取高度
    var pageHeight = document.body.offsetHeight;
    var textareaHeight = pageHeight - 368;
    $('#detail').css("height", textareaHeight);
    // 初始化时间选择器
    $('#range').mobiscroll().range({
        theme: 'material',
        display: 'bottom',
        mode: 'scroller',
        lang: 'zh',
        // dateFormat: 'yyyy-mm-dd',
        controls: ['time'],
        defaultValue: [ new Date(), new Date() ],
        startInput: '#date-start',
        endInput: '#date-end',
    });
    // ================================================================
    // 页面全局变量
    var title, detail, startTime, endTime;
    // 确定开始时间已填写
    $("#date-end-area").click(function(){
        startTime = $('#date-start').val();
        if (startTime === '' || $.trim(startTime) === '') {
            // alert('请先填写开始时间');
            openToast('请先填写开始时间');
        }
    });
    // 向submit键添加click事件
    // 储存新任务
    function submitInsert() {
        title = $('#title').val();
        detail = $('#detail').val();
        startTime = $('#date-start').val();
        endTime = $('#date-end').val();
        if (title === '' || $.trim(title) === '') {
            openToast('标题不能为空');
        }else if (detail === '' || $.trim(detail) === ''){
            openToast('请添加描述');
        }else if (startTime === '' || $.trim(startTime) === ''){
            openToast('请输入任务开始时间');
        }else if (endTime === '' || $.trim(endTime) === ''){
            openToast('请输入任务结束时间');
        }else{
            InsertNewSchedule(title, detail, startTime, endTime);
        };
    };
    // 更新数据
    function submitUpdate() {
        var db = api.require('db');
        var id = api.pageParam.taskId;
        title = $('#title').val();
        detail = $('#detail').val();
        startTime = $('#date-start').val();
        endTime = $('#date-end').val();
        db.openDatabase({
            name: 'inote',
            path: 'fs://inote.db'
        }, function(ret, err){
            if(ret.status){
                // 相关的操作放在这里
                update(id, title, detail, startTime, endTime);
                closeDatabase();
            }
        });
    };
    // 标记为已完成
    function addComplete() {
        api.openFrame({
            name: 'check',
            url: 'check.html',
            bounces: false,
            bgColor: 'rgba(0,0,0,0.4)',
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            }
        });
    };
    // 提示框
    function openToast(msg) {
        api.toast({
            msg: msg,
            duration: 1500,
            location: 'bottom'
        });
    };
    // ===============================================================
    // ===============================================================
    // ===============================================================
    // 数据库操作
    function InsertNewSchedule(title, detail, startTime, endTime) {
        var db = api.require('db');
        db.openDatabase({
            name: 'inote',
            path: 'fs://inote.db'
        }, function(ret, err){
            if(ret.status){
                // 相关的操作放在这里
                insert(title, detail, startTime, endTime);
                closeDatabase();
            }
        });
    };
    function closeDatabase() {
        var db = api.require('db');
        db.closeDatabase({name:'inote'});      
    };
    function executeSql(sql) {
        var db = api.require('db');
        db.executeSql({
            name: 'inote',
            sql: sql
        }, function(ret, err){
            if(ret.status){
                
                api.openWin({name: 'repeat_schedule',reload:true});
                setTimeout(api.closeWin(), 1000);
            }
        });
    };
    function selectSql(sql) {
        var db = api.require('db');
        db.selectSql({
            name:'inote',
            sql: sql
        }, function(ret, err){
            if(ret.status){
                var datas = ret.data;
                // alert( JSON.stringify( datas ) );
                setInputVal(datas);
            }
        });
    };
    // ===============================================================
    // 具体操作
    function insert(title, detail, startTime, endTime) {
        var sql = "INSERT INTO Schedule (type, status, title, detail, startTime, endTime) VALUES (1, 0, '"+title+"', '"+detail+"', '"+startTime+"', '"+endTime+"')";
        executeSql(sql);
    };
    function sel(id) {
        var sql = "SELECT * FROM Schedule WHERE id = "+id+"";
        selectSql(sql);
    };
    function update(id, title, detail, startTime, endTime) {
        var sql = "UPDATE Schedule SET title = '"+title+"', detail = '"+detail+"', startTime = '"+startTime+"', endTime = '"+endTime+"', update_time = CURRENT_TIMESTAMP WHERE id = '"+id+"'";
        executeSql(sql);
    };
    function addStatu(id) {
        var sql = "UPDATE Schedule SET status = '1', update_time = CURRENT_TIMESTAMP WHERE id = '"+id+"'";
        executeSql(sql);
    };
    function del(id) {
        var sql = "DELETE FROM Schedule WHERE id = '"+id+"'";
        executeSql(sql);
    };
    // ===============================================================
    apiready = function(){
        writePagename();
        var name = api.pageParam.name;
        if (name == 'add_repeat_schedule') {
            var rightTab = $('.bar-right');
            rightTab.css("display", "none");
        }

        var id = api.pageParam.taskId;
        var db = api.require('db');
        if (id != '0') {
            $('#submit').addClass('hide');
            db.openDatabase({
                name: 'inote',
                path: 'fs://inote.db'
            }, function(ret, err){
                if(ret.status){
                    sel(id);
                    closeDatabase();
                }
            });
        };
        api.addEventListener({
            name: 'changeStatus'
        }, function( ret, err ){
            if( ret ){
                db.openDatabase({
                    name: 'inote',
                    path: 'fs://inote.db'
                }, function(ret, err){
                    if(ret.status){
                        // 相关的操作放在这里
                        addStatu(id);
                        closeDatabase();
                    }
                });
            }
        });
        // 删除的操作
        api.addEventListener({
            name: 'delete'
        }, function(ret, err){
            if( ret ){
                db.openDatabase({
                    name: 'inote',
                    path: 'fs://inote.db'
                }, function(ret, err){
                    if(ret.status){
                        // 相关的操作放在这里
                        del(id);
                        closeDatabase();
                    }
                });
            }
        });
    };
    // 当打开详情页时，写入默认的数据
    // 写入初始值
    function setInputVal(datas) {
        var data = datas[0];
        var title = data.title;
        var detail = data.detail;
        var startTime = data.startTime;
        var endTime = data.endTime;
        var status = data.status;
        $('#title').val(title);
        $('#detail').val(detail);
        $('#date-start').val(startTime);
        $('#date-end').val(endTime);

        $('#submit').text("已完成");
        $('#submit').addClass("green");
        if (status === '1') {
            $('#title, #detail, #date-start, #date-end').attr('disabled', 'disabled');
        }else{
            // ===========================================
            // 监控表单的变化
            var jsonFormInit = $("form").serialize();
            $('input, textarea').bind('input propertychange', function() {
                var jsonFormCurr = $("form").serialize();
                if (jsonFormCurr != jsonFormInit) {  
                }else{
                    $('#submit2').removeClass('hide');
                };
            });
            $('#date-start').on("change", function() {
                $('#submit2').addClass('hide');
                $('#submit2-1').removeClass('hide');
            });
            $('#date-end').on("change", function() {
                $('#submit2-1').addClass('hide');
                $('#submit2').removeClass('hide');
            });
            // ===========================================
        };
    };
    // =====================================================
    // 添加标题
    function writePagename() {
        var pagename = api.pageParam.pagename;
        $('.title').text(pagename);
    };
    function deleteTask() {
        api.openFrame({
            name: 'delete',
            url: 'delete.html',
            bounces: false,
            bgColor: 'rgba(0,0,0,0.4)',
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            }
        });
    };
</script>
</html>